package com.zero.util;

import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Properties;

/**
 * 数据库操作工具类
 * 
 * @author Zero
 *
 */
public class Jdbc {
	private static Connection con;

	public static void getConnection() throws ClassNotFoundException, SQLException, IOException {
		if (Objects.isNull(con)) {
			// 获取配置文件
			FileInputStream fis = new FileInputStream("cfg/jdbc.properties");
			// 键值对读取信息
			Properties p = new Properties();
			p.load(fis);
			String driverClass = p.getProperty("driverClass");
			String url = p.getProperty("url");
			String username = p.getProperty("username");
			String password = p.getProperty("password");
			// 加载驱动
			Class.forName(driverClass);
			// 得到连接
			con = DriverManager.getConnection(url, username, password);
		}
	}

	/**
	 * 修改数据库，返回影响的行数
	 *
	 * @param sql  要执行的SQL语句
	 * @param args 不定数形参，传入要修改的数据
	 * @return
	 * @throws SQLException
	 */
	public static int update(String sql, Object... args) throws SQLException {
		PreparedStatement ps = con.prepareStatement(sql);

		for (int i = 0; i < args.length; i++) {
			ps.setObject(i + 1, args[i]);
		}

		int result = ps.executeUpdate();

		ps.close();
		return result;
	}

	/**
	 * 查询数据库并把结果集封装成List返回
	 * 
	 * @param sql  要执行的SQL语句
	 * @param args 不定数形参，传入要修改的数据
	 * @return
	 * @throws SQLException
	 */
	public static List<Map<String, Object>> query(String sql, Object... args) throws SQLException {
		List<Map<String, Object>> list = new ArrayList<>();
		PreparedStatement ps = con.prepareStatement(sql);

		for (int i = 0; i < args.length; i++) {
			ps.setObject(i + 1, args[i]);
		}

		ResultSet rs = ps.executeQuery();
		ResultSetMetaData md = rs.getMetaData(); // 获得结果集结构信息,元数据
		int columnCount = md.getColumnCount(); // 获得列数

		while (rs.next()) {
			Map<String, Object> rowData = new HashMap<>(4);
			for (int i = 1; i <= columnCount; i++) {
				rowData.put(md.getColumnName(i), rs.getObject(i));
			}
			list.add(rowData);
		}

		ps.close();
		rs.close();

		return list;
	}

	public static void closeConnection() throws SQLException {
		if (Objects.nonNull(con)) {
			con.close();
			con = null;
		}
	}
}
